package com.team3.ecommerce.controller;

import com.team3.ecommerce.service.UserAuthService;
import com.team3.ecommerce.service.UserAuthServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserAuthServiceImp custuserDetailsService;

    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/index").defaultSuccessUrl("/index",true).failureForwardUrl("/index?error").permitAll()
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/index").permitAll();
        http.authorizeRequests().antMatchers("/user/register","/commodity/Search","/commodity/Details/*","/user/register/checkPhone").permitAll()
                .anyRequest().authenticated();
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略URL
        web.ignoring().antMatchers("/**/*.js", "/lang/*.json", "/**/*.css", "/**/*.map", "/**/*.html",
                "/**/*.png","/**/*.woff2","/**/*.jpg","/**/*.ttf", "/**/*.ico");
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(custuserDetailsService).passwordEncoder(new CustomPasswordEncoder());
        auth.eraseCredentials(false);
    }

}

